package serivce;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Application;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.stereotype.Service;
import untity.FangZhi;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;

@Service
public class MapSerivceImp implements MapService {
    ResourceBundle resourceBundle=ResourceBundle.getBundle("conf/baidu");
    @Override
    public JSONObject getAddress(String ip) {
        String ak=resourceBundle.getString("ak");
        String url="http://api.map.baidu.com/location/ip?ak="+ak+"&ip="+ip+"&coor=bd09ll";
        JSONObject json=this.sendMessage(url);
       return json;
    }

    /**
     * 获取客户端请求终端地址
     * @param request 客户端请求request
     * @return  终端ip地址
     */
    @Override
    public String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    @Override
    public JSONObject getPosition(String address) {
        String ak=resourceBundle.getString("ak");
//        http://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
        String url="http://api.map.baidu.com/geocoding/v3/?address="+address+"&output=json&ak="+ak;
//       http://api.map.baidu.com/geocoding/v3/?address=湖南省长沙市岳麓区&output=json&ak=PAw7ki7r2Zhzx3GcGpaeIFZay5aWDHHq
        JSONObject json=this.sendMessage(url);
        return json;
    }

    @Override
    public JSONObject sendMessage(String url) {
        HttpURLConnection connection = null;
        InputStream is = null;
        JSONObject json=null;
//      String url1="http://api.map.baidu.com/location/ip?ak=PAw7ki7r2Zhzx3GcGpaeIFZay5aWDHHq&ip=176.20.46.167";
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL urlconection = new URL(url);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) urlconection.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：20000毫秒
            connection.setConnectTimeout(100000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(100000);
            // 发送请求

            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                byte[] b=new byte[1024];
                StringBuilder sbf = new StringBuilder();
                while (is.read(b)!=-1){
                    sbf.append(new String(b,"UTF-8"));
                }
                result = sbf.toString();
                System.out.println(result);
                result=new String(result.getBytes("UTF-8"),"UTF-8");
                System.out.println("result="+result);
                json=JSON.parseObject(result);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }

        return json;
    }

    public static void main(String[] args) {
        MapService map=new MapSerivceImp();
        JSONObject jsonObject=map.getPosition("湖南省长沙市岳麓区");
        System.out.println(jsonObject);
    }

}
